// pages/my/borrowingRecords/ndex.js
// 接口
import { fetchBorrowList, fetchBorrowTerm } from '~/request/api';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    keys: {
      value: 'id',
      label: 'name',
    },
    terms: {
      value: null,
      options: [],
    },
    list: [],
    hasLoaded: false,
    loadMoreStatus: 0,
  },

  // 分页变量
  total: 0,
  page: 1,
  page_size: 5,

  // 学期回调
  onChange(e) {
    const { value } = e.detail;
    this.setData({
      'terms.value': value,
    });
    this.page = 1;
    this.borrowList({ term_id: value });
  },

  /**
   * 接口函数
   */

  // 学期
  async getBorrowTerm() {
    try {
      const res = await fetchBorrowTerm();
      const currentId = res?.find((item) => item.is_cur_term == 1)?.id;
      this.setData({ 'terms.options': res, 'terms.value': currentId });
      return currentId;
    } catch (error) {
      console.log(error);
    }
    return this.data.terms.value;
  },

  // 获取借阅记录列表
  async borrowList(params) {
    const { isPage, ..._params } = params;
    const { page, page_size } = this;
    const { list, loadMoreStatus, terms } = this.data;
    const _page = isPage ? page + 1 : page;
    let query = { page: _page, page_size, term_id: terms.value, ..._params };
    if (loadMoreStatus !== 0) return;
    this.setData({
      loadMoreStatus: 1,
    });
    try {
      const res = await fetchBorrowList(query);
      const { data, total } = res;
      if (total === 0) {
        this.total = total;
        this.setData({
          hasLoaded: true,
          loadMoreStatus: 0,
          list: [],
        });
        return;
      }
      const _list = list.concat(data);
      const _loadMoreStatus = list.length === total ? 2 : 0;
      this.page = query?.page || 1;
      this.total = total;
      this.setData({
        list: _list,
        loadMoreStatus: _loadMoreStatus,
      });
    } catch (error) {
      console.log(error);
    }
    this.setData({
      hasLoaded: true,
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const term_id = await this.getBorrowTerm();
    this.borrowList({ term_id });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    const { list } = this.data;
    const { total = 0 } = this;
    if (list.length === total) {
      this.setData({
        loadMoreStatus: 2,
      });
      return;
    }
    this.borrowList({ isPage: true });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
